package com.example.common.listener;

import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.event.GrpcServerStartedEvent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * gRPC服务器启动监听器
 * 监听gRPC服务器启动事件，输出详细的启动成功日志
 * 
 * @author: Allen
 * @create: 2025/1/27 10:00
 * @description: gRPC服务器启动监听器
 **/
@Slf4j
@Component
public class GrpcServerStartupListener {
    
    @Value("${spring.application.name}")
    private String applicationName;
    
    @Value("${server.id}")
    private int serverId;
    
    @Value("${grpc.server.port}")
    private int grpcPort;
    
    @Value("${server.port}")
    private int webPort;
    
    /**
     * 监听gRPC服务器启动事件
     */
    @EventListener
    public void onGrpcServerStarted(GrpcServerStartedEvent event) {
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            
            log.info("🎉 ========================================");
            log.info("🎉 gRPC服务器启动成功！");
            log.info("🎉 ========================================");
            log.info("📋 服务信息:");
            log.info("   服务名称: {}", applicationName);
            log.info("   服务器ID: {}", serverId);
            log.info("   主机地址: {}", hostAddress);
            log.info("   Web端口: {}", webPort);
            log.info("   gRPC端口: {}", grpcPort);
            log.info("");
            log.info("🌐 访问地址:");
            log.info("   Web服务: http://{}:{}", hostAddress, webPort);
            log.info("   gRPC服务: {}:{}", hostAddress, grpcPort);
            log.info("");
            log.info("🔗 服务发现:");
            log.info("   Nacos控制台: http://localhost:8848/nacos");
            log.info("   服务名称: {}", applicationName);
            log.info("");
            log.info("📊 健康检查:");
            log.info("   Web健康检查: http://{}:{}/actuator/health", hostAddress, webPort);
            log.info("   gRPC反射: {}:{} (使用grpcurl测试)", hostAddress, grpcPort);
            log.info("");
            log.info("💡 测试命令:");
            log.info("   # Web服务测试");
            log.info("   curl http://{}:{}/actuator/health", hostAddress, webPort);
            log.info("");
            log.info("   # gRPC服务测试 (需要安装grpcurl)");
            log.info("   grpcurl -plaintext {}:{} list", hostAddress, grpcPort);
            log.info("");
            log.info("🎯 服务状态: ✅ 运行中");
            log.info("🎉 ========================================");
            
        } catch (UnknownHostException e) {
            log.error("❌ 获取主机地址失败", e);
            log.info("🎉 gRPC服务器启动成功！端口: {}", grpcPort);
        }
    }
} 